import React, { useEffect, useState } from "react";
import { ActivityIndicator, Animated, FlatList, RefreshControl, StyleSheet, Text, View } from "react-native";
import { useRouter } from "expo-router";
import Empty from "@/components/empty";

const ProFlatListComponent = function (props) {
    const {
        renderItem,
        pages,
        loading,
        setLoading,
        requestData,
        data,
    } = props;

    const [refreshing, setRefreshing] = useState(false);
    const [refreshingText, setRefreshingText] = useState('下拉刷新');
    const scrollY = new Animated.Value(0); // 用于跟踪滚动偏移

    const router = useRouter();

    // 清除 scrollY 监听器
    useEffect(() => {
        const listenerId = scrollY.addListener(({ value }) => {
            if (!refreshing && value < -100) {
                setRefreshingText('松开刷新');
            } else if (!refreshing && value < 0) {
                setRefreshingText('下拉刷新');
            }
        });

        return () => {
            scrollY.removeListener(listenerId);
        };
    }, [refreshing]);

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing && <View style={styles.refreshHeader}>
            <Text style={styles.refreshText}>{text}</Text>
        </View>
    );

    const handleRefresh = () => {
        setRefreshing(true);
        setRefreshingText('正在刷新...');
        requestData({ pages: 1, intRefreshing: endRefreshing });
    };

    const endRefreshing = () => {
        setRefreshing(false);
        setRefreshingText('下拉刷新');
        setLoading(false);
    };

    const loadMoreData = () => {
        if (loading) return;
        // console.log('加载更多')
        setLoading(true);
        requestData({ pages: pages + 1, intRefreshing: endRefreshing });
    };

    const renderFooter = () => {
        if (!loading || data.length === 0) return null;
        return (
            <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                <ActivityIndicator size="small" />
                <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
            </View>
        );
    };

    return (
        <View style={{ height: "100%" }}>
            <FlatList
                data={data || []} // 确保 data 是一个数组
                renderItem={renderItem}
                keyExtractor={(item, index) => item.id ? item.id.toString() : index.toString()} // 使用唯一标识符，如果有的话
                onEndReached={loadMoreData}
                onEndReachedThreshold={0.5}
                ListFooterComponent={renderFooter}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        onRefresh={handleRefresh} // 绑定刷新函数
                        title={refreshing ? '' : refreshingText}
                        titleColor="#333"
                        // colors={[]} // 隐藏加载图标
                        tintColor="transparent" // 隐藏刷新指示器
                    />
                }
                onScroll={Animated.event(
                    [{ nativeEvent: { contentOffset: { y: scrollY } } }],
                    { useNativeDriver: false }
                )}
                ListHeaderComponent={<RefreshControlHeader refreshing={refreshing} text={refreshingText} />}
                ListEmptyComponent={() => (
                    <Empty/>
                )}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    refreshHeader: {
        alignItems: 'center',
        padding: 20,
    },
    refreshText: {
        fontSize: 12,
        color: '#333',
    },
});

export default ProFlatListComponent;
